package com.k.usbupdate.util

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException

/**
 * 文件工具类
 */
object UFileUtil {

    val TAG = "MFileUtil"

    /**
     * 检查文件是否存在
     *
     * @param filePath 文件路径
     * @return true表示文件存在，false表示文件不存在
     */
    fun isFileExists(filePath: String): Boolean {
        val file = File(filePath)
        return file.exists()
    }

    /**
     * 复制图片文件到指定路径
     *
     * @param sourceFilePath 原图片文件路径
     * @param fileName 图片文件名称（包括后缀）
     * @param destinationDirectory 目标存储目录路径
     * @return true表示复制成功，false表示复制失败
     */
    fun copyImageFile(
        sourceFilePath: String,
        fileName: String,
        destinationDirectory: String
    ): Boolean {
        val sourceFile = File(sourceFilePath)
        if (!sourceFile.exists()) {
            // 源文件不存在，无法复制
            return false
        }

        val destinationDir = File(destinationDirectory)
        if (!destinationDir.exists()) {
            // 目标存储目录不存在，创建目录
            destinationDir.mkdirs()
        }

        val destinationFile = File(destinationDir, fileName)
        if (destinationFile.exists()) {
            // 目标文件已存在，删除目标文件
            destinationFile.delete()
        }

        return try {
            FileInputStream(sourceFile).use { inputStream ->
                FileOutputStream(destinationFile).use { outputStream ->
                    val buffer = ByteArray(4096) // 4KB 缓冲区
                    var bytesRead: Int
                    while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                        outputStream.write(buffer, 0, bytesRead)
                    }
                }
            }
            true
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 从U盘复制文件到下载目录
     */
    fun copyFileFromUsbToDownload(context: Context, usbFilePath: String): String? {
        val usbFile = File(usbFilePath)
        if (!usbFile.exists() || !usbFile.isFile) {
            return null
        }

        val downloadDirectory =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        if (!downloadDirectory.exists()) {
            downloadDirectory.mkdirs()
        }

        val destinationFile = File(downloadDirectory, usbFile.name)

        try {
            FileInputStream(usbFile).use { inputStream ->
                FileOutputStream(destinationFile).use { outputStream ->
                    val buffer = ByteArray(1024)
                    var length: Int
                    while (inputStream.read(buffer).also { length = it } > 0) {
                        outputStream.write(buffer, 0, length)
                    }
                }
            }
            // Return the saved file path
            return destinationFile.absolutePath
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 删除文件夹内的所有内容
     */
    fun deleteFilesInDirectory(directoryPath: String) {
        val directory = File(directoryPath)

        if (directory.exists() && directory.isDirectory) {
            val files = directory.listFiles()
            if (files != null) {
                for (file in files) {
                    if (file.isFile) {
                        Log.e(TAG, "删除文件：" + file.name)
                        file.delete()
                    }
                }
            }
        }
    }
}